package com.bnlr.lrparking.appui.order.stages;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.ByStagesAdapter;
import com.bnlr.lrparking.adapter.ByStagesDetailAdapter;
import com.bnlr.lrparking.appui.bank.SelectByStagesBankActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.event.ApplyStategesEvent;
import com.bnlr.lrparking.event.IsStallPayEvent;
import com.bnlr.lrparking.event.StallPaySucceeEvent;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.ByStagesDetailBean;
import com.bnlr.lrparking.model.StagesBankBean;
import com.bnlr.lrparking.appui.order.OrderRetentionMoneyActivity;
import com.bnlr.lrparking.appui.order.mode.OrderIntentBean;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.view.RingStatisticsView;
import com.bnlr.lrparking.view.SampleEditTextWatcher;
import com.bnlr.lrparking.widget.KeyBordStateUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
 * @author hp
 * @date 2017/11/17
 * 选择分期
 */

public class ByStagesDetailsActivity extends BaseActivity{

    private Unbinder unbinder;
    @BindView(R.id.pie_chart)
    RingStatisticsView pie_chart;//环形图
    @BindView(R.id.recy_bystages)
    RecyclerView recy_bystages;
    @BindView(R.id.ed_bystages)
    ClearEditText ed_bystages;
    @BindView(R.id.tv_downpayment)
    TextView tv_downpayment;//首付
    @BindView(R.id.tv_loans)
    TextView tv_loans;//贷款
    @BindView(R.id.all_price)
    TextView all_price;//总价
    @BindView(R.id.tv_interest)
    TextView tv_interest;//利息
    @BindView(R.id.tv_monthrepay)
    TextView tv_monthrepay;//月供

    @BindView(R.id.imageView61)
    ImageView ivBankPhoto;
    @BindView(R.id.textView51)
    TextView tvBankName;
    private int extendedprice=0;//总价
    private int bystages=0;//首付
    private ByStagesAdapter byStagesAdapter;
    private List<StagesBankBean.DataBean.DrStagesBean> list=new ArrayList<>();
    private float[] mPercent;
    private int fromTag = 0;
    private OrderIntentBean item;
    private int ParkingId;
    private int MAX_INPUT_VALUE = extendedprice;
    private DecimalFormat dformat = new DecimalFormat("##.##");
    private KeyBordStateUtil keyBordStateUtil;
    private int DAI_VALUE;
    private double LIXI_VALUE;
    private  Dialog dialog2;
    private String spaceId;
    private StagesBankBean.DataBean.DrStagesBean sddBean;
    private  double monthPrice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bystagesdetails);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this);
        Intent intent = getIntent();
        fromTag = intent.getIntExtra("enter_stages_from",0);
        if (fromTag == 1) {
            // 从详情中进来
            ParkingId = intent.getIntExtra("park_id",0);
            spaceId = getIntent().getStringExtra("spaceId");
            extendedprice = intent.getIntExtra("zong",0);
            MAX_INPUT_VALUE = extendedprice;
            getStagesBankList();
            initDetailStagesView();
        } else if (fromTag == 2) {
            //  从订单中进来
            item = intent.getParcelableExtra("order_mode");
            extendedprice = item.getDealPrice();
            MAX_INPUT_VALUE = extendedprice;
            ParkingId = item.getParkingId();
            getStagesBankList();
            initOrderStagesView();
        }
        recy_bystages.setLayoutManager(new GridLayoutManager(this,3));
//        initView();
        byStagesAdapter=new ByStagesAdapter(list);
        recy_bystages.setAdapter(byStagesAdapter);
        byStagesAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                byStagesAdapter.setSelectPosition(position);
                byStagesAdapter.notifyDataSetChanged();
                sddBean = list.get(position);

                drawPie();
            }
        });
        keyBordStateUtil=new KeyBordStateUtil(this);
        keyBordStateUtil.addOnKeyBordStateListener(mOnKeyBordStateListener);
        ed_bystages.addTextChangedListener(new SampleEditTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (s.toString() != null && Integer.parseInt(s.toString().equals("")?"0":s.toString()) > MAX_INPUT_VALUE) {
                    ed_bystages.setText(MAX_INPUT_VALUE+"");
                    ed_bystages.setSelection(ed_bystages.getText().toString().length());
                }

            }
        });
        drawPie();
    }
    private KeyBordStateUtil.onKeyBordStateListener mOnKeyBordStateListener = new KeyBordStateUtil.onKeyBordStateListener() {
        @Override
        public void onSoftKeyBoardShow(int keyboardHeight) {
        }
        @Override
        public void onSoftKeyBoardHide() {
            if (!TextUtils.isEmpty(ed_bystages.getText().toString())) {
                int sf = Integer.parseInt(ed_bystages.getText().toString()) +500;
                int shang = sf/1000;
                int value = shang*1000;
                ed_bystages.setText(value+"");
                ed_bystages.setSelection(ed_bystages.getText().toString().length());
            }
            drawPie();
        }
    };
    /**
     * 从订单进来初始化
     */
    private void initOrderStagesView() {
        all_price.setText(extendedprice+"元");
        /*tv_loans.setText(extendedprice+"元");
        tv_interest.setText(((extendedprice-bystages)*rat)+"元");
        mPercent = new float[]{(float) bystages, (float) (extendedprice - bystages) ,(float)((extendedprice-bystages)*rat)};*/
        drawPie();

    }

    /**
     * 画饼
     */
    public void drawPie() {
        if (sddBean == null) {
            return;
        }
        bystages = TextUtils.isEmpty(ed_bystages.getText().toString())? 0 : Integer.parseInt(ed_bystages.getText().toString());
        tv_downpayment.setText(bystages+"元");
        /**
         * 需要贷款额
         */
        tv_loans.setText((extendedprice-bystages)+"元");
        DAI_VALUE = extendedprice-bystages;

        /**
         * 利息
         */
        double yearRate = 0;
        if (sddBean.getYearOrMonth() == 1) {
            yearRate = sddBean.getInterestRate()/100*sddBean.getNumBers();
        } else if (sddBean.getYearOrMonth() == 2) {
            yearRate = sddBean.getInterestRate()/100;
        }
        tv_interest.setText(dformat.format((extendedprice-bystages)*yearRate)+"元");
        LIXI_VALUE = (extendedprice-bystages)*yearRate;
        /**
         * 月供  （年份）
         */
        monthPrice =  (DAI_VALUE+(DAI_VALUE*yearRate))/sddBean.getNumBers();
        tv_monthrepay.setText(dformat.format(monthPrice) + "元("+(sddBean.getNumBers()/12)+"年)");

        /**
         * 总
         */
        float sum = (float)(extendedprice +LIXI_VALUE);
        mPercent = new float[]{((float) bystages)/sum, ((float) DAI_VALUE/sum) ,(float)(LIXI_VALUE/sum)};

        pie_chart.setRingWidth(45f);
        //首付，贷款，利息
        pie_chart.setPercentAndColors(mPercent,new int[]{Color.parseColor("#00CAA3"), Color.parseColor("#FF3333"), Color.parseColor("#e3b56c")});
        pie_chart.refresh();

    }
    /**
     * 从详情进来初始化
     */
    private void initDetailStagesView() {
        all_price.setText(extendedprice+"元");
        drawPie();

    }
    /**
     * 获取分期的银行
     */
    private void getStagesBankList() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.BANK_STAGE, LrConstant.POST);
            mRequest.add("action", "BankStageList");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("parkingId", ParkingId);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<StagesBankBean>(this, true, StagesBankBean.class) {
                        @Override
                        public void doWork(StagesBankBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                if (data.getData() != null && data.getData().size() > 0) {
                                    StagesBankBean.DataBean sbb = data.getData().get(0);
                                    Glide.with(ByStagesDetailsActivity.this).load(sbb.getBankIconUrl()).into(ivBankPhoto);
                                    tvBankName.setText(sbb.getBankName());
                                    list.addAll(sbb.getDrStages());
                                    byStagesAdapter.setNewData(list);
                                    for (int i = 0; i < data.getData().get(0).getDrStages().size(); i++) {
                                        if (data.getData().get(0).getDrStages().get(i).getIsDefault() == 1) {
                                            sddBean = data.getData().get(0).getDrStages().get(i);
                                            break;
                                        }
                                    }
                                    if (fromTag == 1) {
                                        initDetailStagesView();
                                    } else {
                                        initOrderStagesView();
                                    }
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }
    @OnClick({R.id.bystages_back,R.id.select_bystages_bank,R.id.check_stages,R.id.tv_stages_btn})
    public void stagesOnClick(View v) {
        switch (v.getId()){
            case R.id.bystages_back:
                finish();
                break;
            case R.id.select_bystages_bank:
                //  点击选择银行
                startActivityForResult(new Intent(this,SelectByStagesBankActivity.class).putExtra("SelectByStagesBank",ParkingId)
                   ,1004);
                break;
            case R.id.check_stages:
                showDialog();
                break;
            case R.id.tv_stages_btn:
                if (list.size() > 0) {
                    if (fromTag == 1) {
                        if (sddBean == null) {
                            ToastUtils.showShort("请选择分期银行");
                            return;
                        }
                        //  从详情进来点击确定
                        startActivity(new Intent(this,SubmitMessageActivity.class)
                        .putExtra("buy_from",2)
                        .putExtra("spaceId",spaceId)
                        .putExtra("firstPay",ed_bystages.getText().toString())
                        .putExtra("bankId",sddBean.getBankId())
                        .putExtra("stageNumber",sddBean.getNumBers())
                        .putExtra("eachStagePrice", monthPrice));
                    } else {
                        submitByStages();
                    }
                } else {
                    ToastUtils.showShort("请选择要分期的银行");
                }
                break;
            default:
                break;
        }

    }

    /**
     * 提交分期
     */
    private void submitByStages() {
            if (sddBean == null) {
                ToastUtils.showShort("请选择分期银行");
                return;
            }
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "AddBankStage");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("orderId", item.getId());
            mRequest.add("firstPay", ed_bystages.getText().toString());
            mRequest.add("bankId", sddBean.getBankId());
            mRequest.add("stageNumber", sddBean.getNumBers());
            mRequest.add("eachStagePrice", monthPrice);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(this, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                ToastUtils.showShort("提交分期成功");
                                EventBus.getDefault().post(new ApplyStategesEvent());
                                if (item.getStatusInt() == 0) {
                                    startActivity(new Intent(ByStagesDetailsActivity.this, OrderRetentionMoneyActivity.class)
                                            .putExtra("order_bean", item));
                                }
                                finish();
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1004 && resultCode == 1) {
            StagesBankBean.DataBean sbb = data.getParcelableExtra("select_banks");
            Glide.with(ByStagesDetailsActivity.this).load(sbb.getBankIconUrl()).into(ivBankPhoto);
            tvBankName.setText(sbb.getBankName());
            list.clear();
            list.addAll(sbb.getDrStages());
            byStagesAdapter.setIsFirst();
            byStagesAdapter.setNewData(list);
            for (int i = 0; i < sbb.getDrStages().size(); i++) {
                if (sbb.getDrStages().get(i).getIsDefault() == 1) {
                    sddBean = sbb.getDrStages().get(i);
                    break;
                }
            }
            drawPie();
        }
    }
    public void showDialog() {
        View view3 = View.inflate(this,
                R.layout.item_stages_detail_layout, null);
        // 对话框
        dialog2 = new AlertDialog.Builder(this, R.style.Theme_Dialog)
                .create();
        dialog2.show();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog2.getWindow().getAttributes();
        lp.width = (int)(display.getWidth());
        dialog2.getWindow().setAttributes(lp);
        dialog2.getWindow().setWindowAnimations(R.style.dialog_anim_style);
        dialog2.getWindow().setContentView(view3);
        initV(view3);



    }

    private void initV(View view) {
        ImageView ivClose = (ImageView) view.findViewById(R.id.dialog_close);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dialog_rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog2.dismiss();
            }
        });
        List<ByStagesDetailBean> data = new ArrayList<>();
        int monthCount = 0;
        if (sddBean != null) {
            monthCount = sddBean.getNumBers();
        }
        for (int i = 1; i <= monthCount; i++) {
            data.add(new ByStagesDetailBean(("第"+i+"个月"),"¥"+dformat.format((float)DAI_VALUE/monthCount),
                    "¥"+dformat.format((float)(LIXI_VALUE/monthCount))));
        }
        ByStagesDetailAdapter detailAdapter = new ByStagesDetailAdapter(data);
        recyclerView.setAdapter(detailAdapter);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCLose(StallPaySucceeEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIsPay(IsStallPayEvent event) {
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (keyBordStateUtil != null) {
            keyBordStateUtil.removeOnKeyBordStateListener();
        }
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
